
import logging
import dd_legacy_dbtool
import misc_utils
import sharedlogger

MAX_DENYLIST_CNT = 20000

# define in tbl_deny_list
DATA_MAX_LENGTH = 2138

def is_valid_length(data):
    if len(data) > DATA_MAX_LENGTH:
        logging.error('{} is great than {}'.format(data,DATA_MAX_LENGTH))
        return False
    return True

class Code(object):
    SUCESS = 0
    INVALID_STIX_FORMAT = 1
    TOO_MANY_ITEM = 2
    DATA_VALIDATE_DE_DUPLICATE = 3
    CUSTOM_DENYLIST_INVALIDE = 4
    SAVE_DENY_LIST_ERROR = 5

    INVALID_JSON_FORMAT = 7

    UNSUPPORT_TYPE = 8
    UNSUPPORT_DATA = 9
    UNSUPPORT_ID = 10

    LIBRULE_DUPLICATE = 12
    DB_NO_DATA_UPDATE_DELETE = 15

    DATA_EXCEED_MAX_LENGTH = 16

    OTHER_ERROR = 99
    # librule check error code
    REASON_INVALID = 1001
    REASON_DUPLICATE = 1002

class codeException(Exception):
    def __init__(self,code):
        self.code = code

def create_db_connection():
    _p = misc_utils.get_db_params()
    return dd_legacy_dbtool.DBConnection(_p['database'], _p['user'], _password='', _app_name='custdenylist')

def log_init():
    '''
    Get debug level from "level"
    :return:
    '''
    INI_CONF='/opt/TrendMicro/PI/ui/web/htdocs/middleware_rev/lib/logger/logger.ini'

    debug ={
        'ZG_LOG_EMERG': logging.CRITICAL,
        'ZG_LOG_ALERT': logging.CRITICAL,
        'ZG_LOG_CRIT': logging.CRITICAL,
        'ZG_LOG_ERR': logging.ERROR,
        'ZG_LOG_WARNING': logging.WARNING,
        'ZG_LOG_NOTICE': logging.INFO,
        'ZG_LOG_INFO': logging.INFO,
        'ZG_LOG_DEBUG': logging.DEBUG,
        'ZG_LOG_ALL': logging.DEBUG,
        'ZG_LOG_NONE': logging.NOTSET
    }

    debug_levl = debug['ZG_LOG_WARNING']
    msg = None
    try:
        with open(INI_CONF) as f:
            for line in f:
                line = line.strip()
                if line.startswith(';'):continue
                if line.startswith('level'):
                    _, level = line.split('=')
                    level=level.strip().strip('"')
    except:
        msg="Read {} configuration file failed! [{}]".format(INI_CONF,traceback.format_exc())
    else:
        if level in debug:
            debug_levl = debug[level]

    sharedlogger.set_lock_folder('/tmp/')
    sharedlogger.log_rotate_enabled = False
    sharedlogger.reinit('/var/app_data/log/denylist', 'denylist', debug_levl)

    if msg:
        logging.error(msg)

def log_destr():
    sharedlogger.safe_shutdown()
